//
//  SSSafeArray.swift
//  SplendidSwift
//
//  Created by WangYao on 2025/3/18.
//

import UIKit

open class SSSafeArray<Element> {
    private var array: Array<Element> = []
    private let lock = NSLock()
    
    subscript(index: Int) -> Element? {
        get {
            lock.lock()
            defer { lock.unlock() }
            return array.indices ~= index ? array[index] : nil
        }
        
        set {
            lock.lock()
            defer { lock.unlock() }
            if let newValue = newValue, array.indices ~= index {
                array[index] = newValue
            }
        }
    }
    
    var count : Int {
        lock.lock()
        defer { lock.unlock() }
        return array.count
    }
    
    func reserveCapacity(_ count: Int) {
        lock.lock()
        defer { lock.unlock() }
        array.reserveCapacity(count)
    }
    
    func append(_ element: Element) {
        lock.lock()
        defer { lock.unlock() }
        array += [element]
    }
    
    func removeAll() {
        lock.lock()
        defer { lock.unlock() }
        array = []
    }
    
    func forEach(_ body: (Element) -> Void) {
        lock.lock()
        defer { lock.unlock() }
        array.forEach(body)
    }
    
    func first(where predicate: (Element) -> Bool) -> Element? {
        lock.lock()
        defer { lock.unlock() }
        return array.first(where: predicate)
    }
    
    func firstIndex(where predicate: (Element) -> Bool) -> Int? {
        lock.lock()
        defer { lock.unlock() }
        return array.firstIndex(where: predicate)
    }
    
    @discardableResult
    func remove(at index: Int) -> Element {
        lock.lock()
        defer { lock.unlock() }
        return array.remove(at: index)
    }
    
    var isEmpty: Bool {
        lock.lock()
        defer { lock.unlock() }
        return array.isEmpty
    }
    
    //自定义操作
    func operate<Result>(_ done: (Array<Element>) -> Result) -> Result {
        lock.lock()
        defer { lock.unlock() }
        return done(array)
    }
}
